<template>
  <div class="box-border w-full h-full p-10">
    <div class="w-full h-[40px] px-10">
      <div class="flex gap-4">
        <!-- <el-button type="primary" size="large" plain @click="triggerFileSelect"
          >模拟数据导入</el-button
        >
        <input
          ref="fileInputRef"
          type="file"
          accept=".xlsx,.xls"
          style="display: none"
          @change="onFileChange"
        /> -->
        <popover placement="bottom">
          <template #reference>
            <div class="custom-button">管段选择</div>
          </template>
          <div class="w-[195px]">
            <div
              v-for="item in pipelineList"
              :key="item.id"
              class="px-4 py-2 cursor-pointer hover:bg-gray-100"
            >
              <el-checkbox v-model="item.checked" @change="handleSingleCheck(item)">
                {{ item.value }}
              </el-checkbox>
            </div>
          </div>
        </popover>
        <el-button type="primary" size="large" plain @click="runInfer">调令评估</el-button>
        <el-progress :text-inside="true" :stroke-width="20" :percentage="progress" />
      </div>
    </div>
    <div class="mt-8 w-full h-[calc(100%-100px)]">
      <div class="flex items-center justify-between pr-[140px]">
        <div class="flex items-center gap-10">
          <div class="flex items-center gap-3">
            <span>评估结果</span><img src="../../assets/images/downIcon.png" class="w-4 h-5" />
          </div>
          <div class="flex items-center gap-2">
            <span>是否符合水热力安全要求：</span>
            <div
              class="w-[78px] h-[46px] bg-white rounded-md shadow1 flex items-center justify-center"
            >
              <span :class="isSafe ? 'text-lg text-green-600' : 'text-lg text-red-600'">
                {{ isSafe ? '是' : '否' }}
              </span>
            </div>
          </div>
        </div>
      </div>
      <div class="mt-10 w-full h-[calc(100%-100px)] rounded-lg border1">
        <chart-vue :titleName="curPipeName" :chartData="chartData"></chart-vue>
      </div>
    </div>
  </div>
</template>

<script setup>
import ChartVue from './chart.vue'
import * as XLSX from 'xlsx'
import { getInfer } from '@/api/preWarning'
import { useSimulationStore } from '@/stores/modules/simulation'
const simulationStore = useSimulationStore()

const sps_id = computed(() => simulationStore.sps_id)
const fileInputRef = ref(null)
const progress = ref(0)
const chartData = ref({ x: [], score: [], threshold: null, anomalyX: [], anomalyY: [] })
const pipelineList = ref([
  { id: 1, value: '乌-百线', checked: false },
  { id: 2, value: '百-克线', checked: false },
  { id: 3, value: '新81#-701线', checked: false },
  { id: 4, value: '701-总站线', checked: false }
])
const curPipeName = ref('乌-百线')
const isSafe = ref(true) // 新增：安全状态

function handleSingleCheck(selectedItem) {
  curPipeName.value = selectedItem.value
  console.log('🐯 ~ handleSingleCheck ~ curPipeName.value:', curPipeName.value)
  pipelineList.value.forEach((item) => {
    item.checked = item.id === selectedItem.id
  })
  // 切换管线时重置进度条
  progress.value = 0
}

function triggerFileSelect() {
  if (fileInputRef.value) fileInputRef.value.click()
}

let finishTimer = null
function onFileChange(e) {
  const file = e?.target?.files?.[0]
  if (!file) return
  progress.value = 0
  if (finishTimer) {
    clearInterval(finishTimer)
    finishTimer = null
  }

  const reader = new FileReader()
  reader.onprogress = (evt) => {
    if (evt.lengthComputable) {
      const percent = Math.floor((evt.loaded / evt.total) * 90)
      progress.value = Math.min(90, percent)
    }
  }
  reader.onload = (evt) => {
    try {
      const data = evt.target.result
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheetName = workbook.SheetNames[0]
      const firstSheet = workbook.Sheets[firstSheetName]
      const rows = XLSX.utils.sheet_to_json(firstSheet, { header: 1 })
      console.log('导入数据预览:', rows?.slice(0, 5))
    } catch (err) {
      console.error('解析 excel 失败:', err)
    }
    // 平滑补足到 100
    finishTimer = setInterval(() => {
      if (progress.value < 100) {
        progress.value += 2
      } else {
        clearInterval(finishTimer)
        finishTimer = null
      }
    }, 30)
  }
  reader.onerror = () => {
    console.error('文件读取失败')
  }
  reader.readAsArrayBuffer(file)

  // 允许选择同一文件触发 change
  e.target.value = ''
}

// 计算安全状态：检查是否存在异常得分超过阈值的情况
function calculateSafetyStatus() {
  const { score, threshold } = chartData.value
  if (threshold === null || score.length === 0) {
    isSafe.value = true
    return
  }

  // 检查是否有任何得分超过阈值
  const hasExceededThreshold = score.some((scoreValue) => scoreValue > threshold)
  isSafe.value = !hasExceededThreshold
}
// 调令评估：调用 /sps/Infer
async function runInfer() {
  try {
    progress.value = 0
    // 将管段中文名映射为接口要求的 pipe 值
    const map = {
      '乌-百线': 'WBX',
      '百-克线': 'BKX',
      '701-总站线': 'BK_ZZ',
      '新81#-701线': '81#'
    }
    const pipe = map[curPipeName.value] || 'WBX'

    // 先显示缓慢进度到 85
    const step = setInterval(() => {
      if (progress.value < 85) {
        progress.value += 1
      } else {
        clearInterval(step)
      }
    }, 80)

    const { data } = await getInfer({ pipe, sps_id: sps_id.value })

    // 确保第一个定时器已停止，并设置进度为85
    clearInterval(step)
    progress.value = 85

    // 解析返回结构
    const scores = data?.scores_data || []
    const threshold = scores?.[0]?.threshold ?? null
    const x = scores.map((d) => d.index)
    const score = scores.map((d) => d.score)
    const anomalyX = []
    const anomalyY = []
    scores.forEach((d) => {
      if (d.prediction === 1) {
        anomalyX.push(d.index)
        anomalyY.push(d.score)
      }
    })

    chartData.value = { x, score, threshold, anomalyX, anomalyY }

    // 计算安全状态
    calculateSafetyStatus()

    // 平滑补足到 100
    const finisher = setInterval(() => {
      if (progress.value < 100) {
        progress.value = Math.min(100, progress.value + 2)
      } else {
        clearInterval(finisher)
      }
    }, 60)
  } catch (e) {
    console.error('runInfer error:', e)
  }
}
</script>

<style lang="scss" scoped>
.custom-button {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  padding: 8px 20px;
  font-size: 14px;
  border-radius: 4px;
  border: 1px solid #4678b2;
  color: #4678b2;
  background-color: #e8edf4;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    color: white;
    border-color: #5889bf;
    background-color: #4678b2;
  }
}
:deep(.el-progress--line) {
  width: 400px;
}

.shadow1 {
  box-shadow: 3px 3px 13px 0px rgba(0, 0, 0, 0.15);
}

.border1 {
  border: 1px solid #457ab2;
}
</style>
